<?php

/**
 * @author 
 * @copyright 2008
 */
function recurse_select($parent = 0,$level = 0,$table='lights_category_ru',$display = 0)
{
	global $db;
	$str = array();
	$query = "SELECT id,alias,title FROM $table WHERE pid = '".$parent."' AND id<>pid AND status >= '".$display."' GROUP BY alias";
	$sql = $db->fetch_array($query);
	if ($sql!=false and !empty($sql))
	{
		foreach($sql as $k=>$v)
		{	
    		$next_level = $level + 1;
			$str[$v['id']] = array('parent'=>$v,'childs'=>recurse($v['id'], $next_level));
		}
		
	}
	
	return(!empty($str)?$str:false);
}
function recurse($parent = 0, $level = 1, $selected = 0, $display = 0,$level_limiter=0)
{
	global $db, $core_files;

	$pages = array();

	$query = "SELECT id, title, alias, pid FROM ".PFX."category_ru WHERE pid = '$parent' AND status >= '$display' AND id <> '0' ORDER BY order_num";
	$rows = $db->fetch_array($query);

	$i = 0;
	foreach ($rows as $k=>$row)
	{
		$pages[$i]['id'] = $row['id'];
		if (is_array($selected))
		{
            if (in_array($row['id'], $selected))
    		{
    			$pages[$i]['selected'] = 'selected';
    		}
        }
        else
        {
    		if (intval($selected) == $row['id'])
    		{
    			$pages[$i]['selected'] = 'selected';
    		}
    	}
		$pages[$i]['title'] = $row['title'];
		$pages[$i]['level'] = $level;
		$pages[$i]['alias'] = $row['alias'];
		$childs=$db->fetch_one("SELECT count(id) FROM ".PFX."category_ru WHERE pid = '".$row['id']."'");
		if ($childs!=false and $childs[0]>0)
			$pages[$i]['childs']=1;
		else $pages[$i]['childs']=false;

		$next_level = $level + 1;
		if($level_limiter==0 or $next_level<=$level_limiter)
		{
			if ($pages[$i]['childs']!=false)
			{
	            $pages[$i]['sub'] = recurse($row['id'], $next_level, $selected, $display,$level_limiter);
	            $pages[$i]['inside_selected']=true;
			}
			else $pages[$i]['inside_selected']=false;
		}
		$i++;
	}

	return $pages;
}

function for_html_options ($categories,$level='0',$table='lights_category_ru')
{
    $ar=array();
    global $db;
    if($categories!=false)
    {
        foreach($categories as $k=>$v)
        {
            $childs=$db->fetch_one("SELECT count(*) FROM $table WHERE pid='".$v['id']."'");
            if($childs!=false and $childs[0]>0)
            {
                $ar[]=array('id'=>$v['parent']['id'],'title'=>str_repeat('---', $level).$v['parent']['title'],'childs'=>true);
                $next_level=$level+1;
                $ar=array_merge($ar,for_html_options($v['childs'],$next_level));
            }
            else
            {
                $ar[]=array('id'=>$v['parent']['id'],'title'=>str_repeat('---', $level).$v['parent']['title']);
            }
        }
    }
    return $ar;
}
?>